package com.xia.service;

import com.xia.dao.AuthFunctionMapper;
import com.xia.dao.AuthRoleFunctionMapper;
import com.xia.entity.AuthFunction;
import com.xia.entity.AuthFunctionExample;
import com.xia.entity.AuthRoleFunctionExample;
import com.xia.utils.IDUtils;
import org.apache.tomcat.util.descriptor.web.WebXml;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class FunctionService {

    private final AuthFunctionMapper functionMapper;
    private final AuthRoleFunctionMapper roleFunctionMapper;

    @Autowired(required = false)
    public FunctionService(AuthFunctionMapper functionMapper, AuthRoleFunctionMapper roleFunctionMapper) {
        this.functionMapper = functionMapper;
        this.roleFunctionMapper = roleFunctionMapper;
    }

    public void addFunction(AuthFunction function) {
        function.setId(IDUtils.genItemId());
        this.functionMapper.insert(function);
    }

    public void updateUrl(Long id, String url) {
        AuthFunction function = new AuthFunction();
        function.setUrl(url);
        this.functionMapper.updateByPrimaryKeySelective(function);
    }

    public List<AuthFunction> getFunctions(Long parentId) {
        AuthFunctionExample example = new AuthFunctionExample();
        AuthFunctionExample.Criteria cri = example.createCriteria();
        cri.andParentIdEqualTo(parentId);
        return this.functionMapper.selectByExample(example);
    }

    @Transactional
    public void deleteFunction(Long id) {
        this.functionMapper.deleteByPrimaryKey(id);
        AuthRoleFunctionExample example = new AuthRoleFunctionExample();
        AuthRoleFunctionExample.Criteria cri = example.createCriteria();
        cri.andFunctionIdEqualTo(id);
        this.roleFunctionMapper.deleteByExample(example);
    }

    public List<AuthFunction> getFunctions() {
        return this.functionMapper.selectByExample(new AuthFunctionExample());
    }
}
